<?php
class TagFilter extends AbstractFilter {

	public $tag;
	
	protected $_criteria = null;
	
	public function init($criteria) {
		$this->_criteria = $criteria;
		if (isset($_GET['tag'])) $this->tag = explode('_', $_GET['tag']);
	}
	
	public function apply() {
		if (!empty($this->tag)) {
			$tagIds = implode(',', $this->tag);
			$this->_criteria->alias = 'p';
			$this->_criteria->addJoin(PostTag::model()->tableName(), "p.id=pt.post_id AND pt.tag_id IN ($tagIds)", 'JOIN', 'pt');
		}
	}

	public function getClearUrl() {
		$gets = $_GET;
		unset($gets['tag']);
		return Yii::app()->createAbsoluteUrl('site/index', $gets);
	}
	
	public function isApplied() {
		return isset($_GET['tag']);
	}
	
	public function getItems() {
		$t = Tag::model()->tableName();
		$pt = PostTag::model()->tableName();
		$c = clone $this->_criteria;
		$c->removeJoin($pt);
		$c->group = 't.id';
		$c->select = 't.id, t.name, count(p.id) as count';
		$c->addJoin($pt, 'p.id=pt.post_id', 'JOIN', 'pt');
		$c->addJoin($t, 'pt.tag_id=t.id', 'JOIN', 't');
		$cmd = $c->getCommand();
		$cmd->from = Post::model()->tableName().' AS p';
		
		$data = $cmd->queryAll();
		$result = array();
		foreach($data as $d) {
			$result[$d['id']] = $d['name'].' <span class="count">('.$d['count'].')</span>';
		}
		return $result;
	}
	
	public function getTemplate() {
		return '/catalog/filter/tag';
	}

}